import * as faceapi from "face-api.js";

const classes = ['amy', 'bernadette', 'howard', 'leonard', 'penny', 'raj', 'sheldon', 'stuart']

main()

async function main(){
    // load model
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights');

    const faceMatcher = await createBbtFaceMatcher(1)

  
    const imgUris = classes.map(className=>{
        return [...Array(5)].map((_,index)=> getImageUri(className,index+1) )
    }).reduce((arr,arr2)=>arr.concat(arr2))

    const images = await Promise.all(imgUris.map(async img=>faceapi.fetchImage(img))) 
    
    const descriptorsByFace = await Promise.all(images.map(async image=>faceapi.computeFaceDescriptor(image)))
    descriptorsByFace.forEach((descriptor,i)=>{
        const canvas = faceapi.createCanvasFromMedia(images[i])
        const dom = document.getElementById('faceContainer')
        dom.appendChild(canvas)
        const ctx = faceapi.getContext2dOrThrow(canvas)
        ctx.font = '16px Georgia'
        ctx.fillStyle = 'red'
        ctx.fillText(faceMatcher.findBestMatch(descriptor).toString(), 20, canvas.height-20)
    })

    closeLoading()
}


// 样本识别
async function createBbtFaceMatcher(num){
    let labeledFaceDescriptors = await Promise.all(classes.map(async className=>{
        const uri = getImageUri(className, num)
        const img = await faceapi.fetchImage(uri)
        const descriptors = [await faceapi.computeFaceDescriptor(img)]
        return new faceapi.LabeledFaceDescriptors(className, descriptors)
    }))

    return new faceapi.FaceMatcher(labeledFaceDescriptors)
}


// 获取图片
function getImageUri(className,num){
    return 'http://127.0.0.1:8888/images/'+className+'/'+className+num+'.png'
}